<?php

namespace StudyBuddy\Controllers;

use StudyBuddy\SocialCheckboxes;

use StudyBuddy\WebPage;
use StudyBuddy\RegBlockQuickReg;
use StudyBuddy\RegBlock;
use StudyBuddy\Template\Urhere;
use StudyBuddy\LoginForm;

/**
 * Class for displaying the "Ask question" Form
 *
 */
class Askform extends WebPage
{

	protected $permission = 'ask';

	/**
	 * Form object
	 *
	 * @var object of type \StudyBuddy\Forms\Askform
	 */
	protected $oForm;

	protected $qtab = 'ask';

	protected $title;

	/**
	 *
	 * Layout 1 means no side columns - just one main area
	 * @var int
	 */
	protected $layoutID = 1;



	/**
	 * Main entry point
	 * for this class
	 * (non-PHPdoc)
	 * @see WebPage::main()
	 */
	protected function main(){
		$this->aPageVars['title'] = $this->title = $this->_('Ask a question');

		$this->addMetas()
		->configureEditor()
		->makeForm()
		->setMustLogin()
		->setForm()
		->makeTopTabs()
		->makeMemo()
		->makeHintBlocks()
		->makeRecentTags()
		->makeRecentActivites()
		->makeTutorListing();
	}


	/**
	 * Add extra meta tags to indicate
	 * that user has or does not have
	 * blogger and tumblr Oauth keys
	 *
	 * @return object $this
	 */
	protected function addMetas(){
		$this->addMetaTag('tm', (null !== $this->oRegistry->Viewer->getTumblrToken()));
		$this->addMetaTag('blgr', (null !== $this->oRegistry->Viewer->getBloggerToken()));
		$this->addMetaTag('linkedin', (null !== $this->oRegistry->Viewer->getLinkedInToken()));

		return $this;
	}


	/**
	 * Instantiate the $this->oForm object
	 * and sets the value of 'social' var
	 *
	 * @return object $this
	 */
	protected function makeForm(){

		$this->oForm = new \StudyBuddy\Forms\Askform($this->oRegistry);
		if(!$this->oForm->isSubmitted()){
			$this->oForm->socials = SocialCheckboxes::get($this->oRegistry);
		}

		return $this;
	}


	/**
	 * Set the value of $this->aPageVars['body']
	 * to the html of the form
	 *
	 * @return object $this
	 */
	protected function setForm(){

		/**
		 * In case of Ajax can just return the form now
		 */
		$this->aPageVars['body'] = $this->oForm->getForm();

		return $this;
	}


	protected function makeTopTabs(){
                $guest = null;
                if($this->oRegistry->Viewer->isGuest()) {
                    $guest['link_ask'] = '#'; // 13
                    $guest['link_ask_click'] = ' onclick="oSL.getQuickRegForm()"'; //14
                }
		$tabs = Urhere::factory($this->oRegistry)->get('tplToptabs', $this->qtab, $guest);
		$this->aPageVars['topTabs'] = $tabs;

		return $this;
	}

	//hoangto tutor listing
	protected function makeTutorListing(){

		$s = $this->getSortedTutors();
		$tutors = \tplTutorBox::parse(array('tutors' => $s, 'title' => $this->_('Tutor Listing')));
		d('cp');
		$this->aPageVars['tutors'] = $tutors;

		return $this;
	}
	
	//hoangto tutor listing loop
	protected function getSortedTutors() {
		
		$cur = $this->oRegistry->Mongo->USERS->find(array('tmp_role' => 'tutor'))->sort(array('experience' => -1))->limit(9);

		$canTeach = '';
		
		$func = function(&$a) use($canTeach){
			$a['canTeach'] = $canTeach;
		};
		
		$tutors = \tplTutorListing::loop($cur, true, $func);
		
		return $tutors;
	}
	
	//hoangto tutor listing
	protected function makeRecentActivites(){

		$s = $this->getSortedActivities();
		$tutors = \tplActivityBox::parse(array('ractivites' => $s, 'title' => $this->_('Recent activities')));
		d('cp');
		$this->aPageVars['activities'] = $tutors;

		return $this;
	}
	
	//hoangto tutor listing loop
	protected function getSortedActivities() {
	
		$act_link = '';
		
		$func = function(&$a) use($act_link){
			$a['act_link'] = $act_link;
		};
		
		$cur = $this->oRegistry->Mongo->ACTIVITIES->find()->sort(array('i_ts' => -1))->limit(5);
			
		$tutors = \tplActivityList::loop($cur, true, $func);
		
		return $tutors;
	}
	
	protected function makeRecentTags(){

		$aUserTags = $this->oRegistry->Viewer['a_f_t'];
		if(!empty($aUserTags)){
			$s = $this->getSortedRecentTags($aUserTags);
		} else {
			$s = $this->oRegistry->Cache->get('qrecent');
		}

		$tags = \tplBoxrecent::parse(array('tags' => $s, 'title' => $this->_('Recent Tags')));
		d('cp');
		$this->aPageVars['tags'] = $tags;

		return $this;
	}
	
	protected function getSortedRecentTags(array $aUserTags, $type = 'recent'){

		$limit = 9;
		if('unanswered' === $type){
			$cur = $this->oRegistry->Mongo->UNANSWERED_TAGS->find(array(), array('tag', 'i_count'))->sort(array('i_ts' => -1))->limit($limit);
		} else {
			$cur = $this->oRegistry->Mongo->QUESTION_TAGS->find(array('i_count' => array('$gt' => 0)), array('tag', 'i_count'))->sort(array('i_ts' => -1))->limit($limit);
		}

		d('got '.$cur->count(true).' tag results');
		$aTags = iterator_to_array($cur);

		d('aTags: '.print_r($aTags, 1));

		if(!empty($aTags)){
			usort($aTags, function($a, $b) use ($aUserTags){
				return (in_array($a['tag'], $aUserTags)) ? -1 : 1;
			});
		};

		d('$aTags now: '.print_r($aTags, 1));
		$html = ('unanswered' === $type) ? \tplUnanstags::loop($aTags) : \tplLinktag::loop($aTags);

		d('html recent tags: '.$html);

		return '<div class="tag"><ul>'.$html.'</ul></div>';
	}


	/**
	 * @todo translate this
	 *
	 * @return object $this
	 */
	protected function makeMemo(){
		$memo = '<strong>'.$this->_('Ask question relevant to this community').'</strong>
		<ul>
		<li>Provide enough details</li>
		<li>Be clear and concise</li>
		<li>Provide tags relevant to your question</li>
		</ul>';

		$this->aPageVars['qheader'] = '<div class="memo">'.$memo.'</div>';

		return $this;
	}


	protected function makeHintBlocks(){

		return $this;
	}

	/**
	 * Set classnames based on user logged in status
	 * not logged in user will get com_hand class
	 * which in turn will trigger popup on click
	 * on the form element
	 *
	 * @return object $this
	 */
	protected function setMustLogin(){

		if(!$this->isLoggedIn()){
			$this->oForm->qbody = $this->_('Please login to post your question');
			$this->oForm->com_hand = ' com_hand';
			$this->oForm->readonly = 'readonly="readonly"';
			$this->oForm->disabled = ' disabled="disabled"';

			$oQuickReg = new RegBlockQuickReg($this->oRegistry);

			$socialButtons = LoginForm::makeSocialButtons($this->oRegistry);
			/**
			 * @todo Translate string
			 */
			if(!empty($socialButtons)){
				$this->oForm->connectBlock = '<div class="com_connect"><h3>'.$this->_('Join with account you already have').'</h3>'.$socialButtons.'</div>';
			}
		}

		return $this;
	}

}
